package logic

import (
	"context"
	"shop-manager/internal/do"
	"shop-manager/internal/repos/factory_rebate"
	"shop-manager/internal/repos/goods"
	"shop-manager/internal/vo"
	"shop-manager/utils"

	"github.com/samber/lo"
)

//go:generate newc
type FactoryRebateLogic struct {
	factoryRebateRepo *factory_rebate.FactoryRebateRepo
	goodsRepo         *goods.GoodsRepo
	goodsLogic *GoodsLogic
}

func (l *FactoryRebateLogic) ListFactoryRebate(ctx context.Context, req vo.ListFactoryRebateReq) (rsp *vo.ListFactoryRebateRsp, err error) {
	// 条码转为商品ID
	var goodsIDs []int
	if len(req.BarCode) > 0 {
		barCodes := utils.SplitString(req.BarCode, ",;")
		goodsList, _, err := l.goodsRepo.ListGoods(ctx, goods.ListGoodsParam{
			BarCodes: barCodes,
			PageSize: do.PageSizeNoLimit,
		})
		if err != nil {
			return nil, err
		}
		goodsIDs = lo.Map(goodsList, func(item *do.Goods, index int) int {
			return item.ID
		})
	}

	listData, total, err := l.factoryRebateRepo.ListFactoryRebate(ctx, factory_rebate.ListFactoryRebateParam{
		Page:     req.Page,
		PageSize: req.PageSize,
		GoodsIDs: goodsIDs,
		Search:   req.Search, // 品牌
	})
	if err != nil {
		return nil, err
	}

	rsp = &vo.ListFactoryRebateRsp{
		Items: make([]*vo.FactoryRebate, 0, len(listData)),
		Total: total,
	}

	dbGoodsIds := lo.Map(listData, func(item *do.FactoryRebate, index int) int {
		return item.GoodsID
	})
	goodsMap := make(map[int]*vo.Goods, len(dbGoodsIds))
	if len(dbGoodsIds) > 0 {
		goodsListRsp, err := l.goodsLogic.ListGoods(ctx, vo.ListGoodsReq{
			IDs: dbGoodsIds,
			PageSize: do.PageSizeNoLimit,
		})
		if err != nil {
			return rsp, err
		}

		for _, goods := range goodsListRsp.Items {
			goodsMap[goods.ID] = goods
		}
	}

	// 组装返回数据
	for _, rebate := range listData {
		goodsInfo := goodsMap[rebate.GoodsID]
		item := &vo.FactoryRebate{
			ID:                 rebate.ID,
			GoodsID:            rebate.GoodsID,
			Rebate:             float64(rebate.Rebate),
			ValidityStartTime:  rebate.ValidityStartTime,
			ValidityEndTime: rebate.ValidityEndTime,
			CreatedAt:          rebate.CreatedAt,
			UpdatedAt:          rebate.UpdatedAt,
			Goods: goodsInfo,
		}
		rsp.Items = append(rsp.Items, item)
	}

	return rsp, nil
}

func (l *FactoryRebateLogic) CreateFactoryRebate(ctx context.Context, req vo.CreateFactoryRebateReq) (rsp *vo.CreateFactoryRebateRsp, err error) {
	// 检查商品ID是否存在
	goodsList, _, err := l.goodsRepo.ListGoods(ctx, goods.ListGoodsParam{
		IDs: []int{req.GoodsID},
	})
	if err != nil {
		return nil, err
	}
	if len(goodsList) == 0 {
		return nil, utils.NewErrorf("商品ID[%d]不存在", req.GoodsID)
	}

	// 创建返点记录
	rebateID, err := l.factoryRebateRepo.CreateFactoryRebate(ctx, &do.FactoryRebate{
		GoodsID:            req.GoodsID,
		Rebate:             req.Rebate,
		ValidityStartTime:  req.ValidityStartTime,
		ValidityEndTime: req.ValidityEndTime,
	})
	if err != nil {
		return nil, err
	}

	return &vo.CreateFactoryRebateRsp{
		ID: rebateID,
	}, nil
}

func (l *FactoryRebateLogic) UpdateFactoryRebate(ctx context.Context, req vo.UpdateFactoryRebateReq) (err error) {
	// 检查返点记录是否存在
	rebates, _, err := l.factoryRebateRepo.ListFactoryRebate(ctx, factory_rebate.ListFactoryRebateParam{
		GoodsIDs: []int{},
	})
	if err != nil {
		return err
	}
	if len(rebates) == 0 {
		return utils.NewError("返点记录不存在")
	}

	// 更新返点记录
	return l.factoryRebateRepo.UpdateFactoryRebate(ctx, &do.FactoryRebate{
		ID:                 req.ID,
		Rebate:             float32(req.Rebate),
		ValidityStartTime:  req.ValidityStartTime,
		ValidityEndTime: req.ValidityEndTime,
	})
}

func (l *FactoryRebateLogic) DeleteFactoryRebate(ctx context.Context, req vo.GetFactoryRebateReq) (err error) {
	// 检查返点记录是否存在
	exists, _, err := l.factoryRebateRepo.ListFactoryRebate(ctx, factory_rebate.ListFactoryRebateParam{
		IDs: []int{req.ID},
	})
	if err != nil {
		return err
	}
	if len(exists) == 0 {
		return utils.NewError("返点记录不存在")
	}

	// 删除返点记录
	return l.factoryRebateRepo.DeleteFactoryRebate(ctx, req.ID)
}

func (l *FactoryRebateLogic) GetFactoryRebate(ctx context.Context, req vo.GetFactoryRebateReq) (rsp *vo.GetFactoryRebateRsp, err error) {
	// 获取返点记录
	rebate, err := l.factoryRebateRepo.GetFactoryRebate(ctx, req.ID)
	if err != nil {
		return nil, err
	}
	if rebate == nil {
		return nil, utils.NewError("返点记录不存在")
	}

	// 获取关联的商品信息
	goodsInfos, _, err := l.goodsRepo.ListGoods(ctx, goods.ListGoodsParam{
		IDs: []int{rebate.GoodsID},
	})
	if err != nil {
		return nil, err
	}
	if len(goodsInfos) == 0 {
		return nil, utils.NewError("商品不存在")
	}
	goodsInfo := goodsInfos[0]

	// 组装返回数据
	voRebate := &vo.FactoryRebate{
		ID:                 rebate.ID,
		GoodsID:            rebate.GoodsID,
		Rebate:             float64(rebate.Rebate),
		ValidityStartTime:  rebate.ValidityStartTime,
		ValidityEndTime: rebate.ValidityEndTime,
		CreatedAt:          rebate.CreatedAt,
		UpdatedAt:          rebate.UpdatedAt,
	}

	// 设置商品信息
	if goodsInfo != nil {
	}

	return &vo.GetFactoryRebateRsp{
		FactoryRebate: voRebate,
	}, nil
}

// BatchUpdateFactoryRebate 批量更新厂家返点
func (l *FactoryRebateLogic) BatchUpdateFactoryRebate(ctx context.Context, req vo.BatchUpdateFactoryRebateReq) error {
	// 验证返点值范围
	if req.Rebate < 0 || req.Rebate > 1 {
		return utils.NewError("返点百分比必须在0-100之间")
	}

	// 验证商品ID列表
	if len(req.GoodsIDs) == 0 {
		return utils.NewError("商品ID列表不能为空")
	}

	// 开始事务处理
	return l.factoryRebateRepo.BatchUpdateRebates(ctx, req.GoodsIDs, float32(req.Rebate), req.ValidityStartTime, req.ValidityEndTime)
}
